package com.yuma.redissondemo.controller;

import org.redisson.api.RCountDownLatch;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class RedissonController {

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/read")
    public String testRead() {
        RReadWriteLock rwLock = this.redissonClient.getReadWriteLock("rwLock");
        rwLock.readLock().lock(10, TimeUnit.SECONDS);  // 10秒后自动解锁
        // TODO 一堆读
        // ....
        //rwLock.readLock().unlock();
        return "测试读锁";
    }

    @GetMapping("/write")
    public String testWrite() {
        RReadWriteLock rwLock = this.redissonClient.getReadWriteLock("rwLock");
        rwLock.writeLock().lock(10, TimeUnit.SECONDS);
        // TODO 一堆写
        //rwLock.writeLock().unlock();
        return "测试写锁";
    }

    @GetMapping("/latch")
    public String testLatch() {
        try {
            RCountDownLatch cdl = this.redissonClient.getCountDownLatch("cdl");
            cdl.trySetCount(6);
            cdl.await();  // 阻塞，等待所有学生锁门
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "班长锁上了门";
    }

    @GetMapping("/cd")
    public String testCountDown() {
        RCountDownLatch cdl = this.redissonClient.getCountDownLatch("cdl");
        cdl.countDown();
        return "出来一个学生";
    }
}
